package com.yeren.servlet.tarena.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ListEmpServlet extends HttpServlet {
	/*
	 * 使用请求中的name,contact两组参数值 分别使用getParameter和getParameterValues方法获取
	 */
	public void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		// 保证正确输出中文
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out = resp.getWriter();
		
		// 
		Connection conn = null;
		PreparedStatement stat = null;
		ResultSet rs=null;
		try {
			Class.forName("oracle.jdbc.OracleDriver");
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott", "tiger");
			stat = conn.prepareStatement("select * from liu_temp");
			rs=stat.executeQuery();
			//2.输出表格之前的页面标记
			out.println("<HTML>");
			out.println("<HEAD></HEAD>");
			out.println("<BODY>");
			out.println("<table border='1' cellpadding='0' cellspacing='0' width='800px'>");
			out.println("<caption>员工信息</caption>");
			out.println("<tr><td>编号</td><td>姓名</td><td>薪水</td><td>年龄</td><td>删除操作</td><td>修改</td></tr>");
			//3.遍历结果集，以表格形式输出数据
			while(rs.next()){
				int id=rs.getInt("id");
				String name=rs.getString("name");
				double salary=rs.getDouble("salary");
				int age=rs.getInt("age");
				out.println("<tr>" +
						"<td>"+id+"</td>" +
						"<td>"+name+"</td>" +
						"<td>"+salary+"</td>" +
						"<td>"+age+"</td>");
				out.println("<td><a href='delete?id="+id+"' "+"onclick=\"return confirm('是否确定删除"+name+"');\">删除</a></td>");
				out.println("<td><a href='load?id="+id+"'>修改</a></td>");
				out.println("</tr>");
			}
			out.print("</table>");
			out.println("</BODY>");
			out.println("</HTML>");
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			out.print("系统繁忙，稍后重试");
		} finally {         
			if (conn != null) {
				try {
					conn.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}
}
